<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品管理</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="/css/index.css">
    <!-- 引入组件库 -->
    <script src="/js/vue.js"></script>
    <script src="/js/index.js"></script>
    <script src="/js/axios.min.js"></script>
    <style>
        /* 原有样式保持不变 */
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
        }
        .card-container {
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
            overflow: hidden;
        }
        .toolbar {
            padding: 16px 20px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }
        .filter-item {
            display: inline-block;
            margin-right: 10px;
        }
        .table-container {
            padding: 20px;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
            border-radius: 4px;
            overflow: hidden;
        }
        .table th, .table td {
            padding: 10px;
            border: 1px solid #e9e9e9;
            text-align: left;
        }
        .table th {
            background-color: #f7f8fa;
            font-weight: 500;
        }
        .table tr:hover {
            background-color: #fafafa;
        }
        .pagination-container {
            padding: 16px 20px;
            border-top: 1px solid #f0f0f0;
            text-align: right;
        }
        .status-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            line-height: 1;
        }
        .status-pending {
            background-color: #fff2e8;
            color: #ff7d00;
        }
        .status-review {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        .status-passed {
            background-color: #e8f4ea;
            color: #00b42a;
        }
        .operation-buttons {
            display: flex;
            gap: 5px;
        }
        .btn {
            padding: 5px 12px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary {
            background-color: #1890ff;
            color: #fff;
        }
        .btn-warning {
            background-color: #faad14;
            color: #fff;
        }
        .btn-danger {
            background-color: #ff4d4f;
            color: #fff;
        }
        .btn-default {
            background-color: #f5f5f5;
            color: #333;
        }
        .dialog {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 50%;
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
        }
        .dialog-header {
            padding: 16px 20px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .dialog-body {
            padding: 20px;
        }
        .dialog-footer {
            padding: 12px 20px;
            border-top: 1px solid #f0f0f0;
            text-align: right;
        }
        .form-item {
            margin-bottom: 18px;
        }
        .form-label {
            display: inline-block;
            width: 100px;
            text-align: right;
            margin-right: 10px;
        }
        .form-control {
            width: calc(100% - 110px);
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .input-number {
            width: calc(100% - 110px);
        }
        textarea.form-control {
            min-height: 80px;
            resize: vertical;
        }
        .page-title {
            font-size: 18px;
            font-weight: 600;
            color: #1f2d3d;
            margin-bottom: 15px;
            padding-left: 20px;
            padding-top: 10px;
        }
        .date-container {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .date-label {
            color: #666;
            white-space: nowrap;
        }
        .hidden {
            display: none;
        }
        .mask {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }
        .select {
            width: calc(100% - 110px);
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
        }

        /* 新增分页样式 */
        .pagination {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .page-number {
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #d9d9d9;
            background: #fff;
            cursor: pointer;
        }
        .page-number:hover {
            border-color: #1890ff;
            color: #1890ff;
        }
        .page-number.active {
            background-color: #1890ff;
            color: white;
            border-color: #1890ff;
        }
        .ellipsis {
            padding: 0 5px;
            color: #666;
        }
    </style>
</head>
<body>
<div id="app">
    <h3 class="page-title">商品入库管理</h3>

    <!-- 主内容卡片 -->
    <div class="card-container">
        <!-- 工具栏 -->
        <div class="toolbar">
            <button class="btn btn-primary" @click="showAddDialog">
                添加入库信息
            </button>
            <input type="text" v-model="searchForm.id" placeholder="请输入入库ID" style="width: 200px;" class="filter-item form-control">
            <input type="text" v-model="searchForm.productName" placeholder="请输入商品名称" style="width: 200px;" class="filter-item form-control">

            <!-- 单个创建日期搜索 -->
            <div class="date-container">
                <span class="date-label">创建日期:</span>
                <input type="date" v-model="searchForm.createTime" class="form-control" style="width: 200px;">
            </div>

            <button class="btn btn-primary" @click="loadData">
                查询
            </button>
            <button class="btn btn-warning" @click="batchStockIn">
                批量提交
            </button>
            <button class="btn btn-default" @click="resetSearch">
                重置
            </button>
        </div>

        <!-- 数据表格 -->
        <div class="table-container">
            <table class="table">
                <thead>
                <tr>
                    <th><input type="checkbox" @change="checkAll($event)"></th>
                    <th>入库ID</th>
                    <th>产品名</th>
                    <th>入库数量</th>
                    <th>单价</th>
                    <th>总金额</th>
                    <th>供应商</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <th>入库时间</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="row in tableData" :key="row.inId">
                    <td><input type="checkbox" v-model="row.checked" @change="handleCheck(row)"></td>
                    <td>{{ row.inId }}</td>
                    <td>{{ row.productName }}</td>
                    <td>{{ row.quantity }}</td>
                    <td>{{ formatPrice(row.price) }}</td>
                    <td>{{ formatPrice(row.amount) }}</td>
                    <td>{{ row.supplier }}</td>
                    <td>
                        <span :class="getStatusCode(row.status)">{{ getStatusText(row.status) }}</span>
                    </td>
                    <td>{{ row.createTime }}</td>
                    <td>{{ row.completeTime || '-' }}</td>
                    <td>{{ row.remark || '-' }}</td>
                    <td>
                        <div class="operation-buttons">
                            <button class="btn btn-primary" @click="handleEdit(row)" :disabled="row.status !== 1" style="padding: 2px 8px; font-size: 12px;">
                                提交审核
                            </button>
                            <button class="btn btn-danger" @click="handleDelete(row)" style="padding: 2px 8px; font-size: 12px;">
                                删除
                            </button>
                        </div>
                    </td>
                </tr>
                <tr v-if="tableData.length === 0">
                    <td colspan="12" style="text-align: center;">暂无数据</td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页（优化后） -->
        <div class="pagination-container">
            <div class="pagination">
                共 {{ total }} 条记录，总页数：{{ totalPages }}
                <button class="btn btn-default" @click="changePage(1)" :disabled="pageNum === 1">首页</button>
                <button class="btn btn-default" @click="changePage(pageNum - 1)" :disabled="pageNum <= 1">上一页</button>

                <!-- 页码按钮 -->
                <template v-for="page in pageNumbers" :key="page">
                    <span class="ellipsis" v-if="page === '...'">...</span>
                    <button
                            class="page-number"
                            :class="{ 'active': page === pageNum }"
                            @click="changePage(page)"
                            v-else>
                        {{ page }}
                    </button>
                </template>

                <button class="btn btn-default" @click="changePage(pageNum + 1)" :disabled="pageNum >= totalPages">下一页</button>
                <button class="btn btn-default" @click="changePage(totalPages)" :disabled="pageNum === totalPages">末页</button>

                <select v-model="pageSize" @change="handleSizeChange" class="form-control" style="width: auto; display: inline-block;">
                    <option value="10">10条/页</option>
                    <option value="20">20条/页</option>
                    <option value="50">50条/页</option>
                    <option value="100">100条/页</option>
                </select>
            </div>
        </div>
    </div>

    <!-- 添加/编辑商品对话框 -->
    <div class="mask" v-if="dialogVisible"></div>
    <div class="dialog" v-if="dialogVisible">
        <div class="dialog-header">
            <h3>{{ dialogTitle }}</h3>
            <button class="btn btn-default" @click="dialogVisible = false">×</button>
        </div>
        <div class="dialog-body">
            <div class="form-item">
                <label class="form-label">供应商</label>
                <select class="select" v-model="form.supplier" @change="validate('supplier')">
                    <option value="">请选择供应商</option>
                    <option v-for="supplier in supplierlist" :value="supplier.supplierName" :key="supplier.id">
                        {{ supplier.supplierName }}
                    </option>
                </select>
                <div v-if="errors.supplier" style="color: #ff4d4f; margin-left: 110px; margin-top: 5px; font-size: 12px;">
                    {{ errors.supplier }}
                </div>
            </div>

            <div class="form-item">
                <label class="form-label">商品</label>
                <select class="select" v-model="form.productId" @change="validate('productId')">
                    <option value="">请选择入库的商品</option>
                    <option v-for="item in products" :value="item.id" :key="item.id">
                        {{ item.productName }}
                    </option>
                </select>
                <div v-if="errors.productId" style="color: #ff4d4f; margin-left: 110px; margin-top: 5px; font-size: 12px;">
                    {{ errors.productId }}
                </div>
            </div>

            <div class="form-item">
                <label class="form-label">数量</label>
                <input type="number" class="form-control input-number" v-model="form.quantity" min="1" @blur="validate('quantity')">
                <div v-if="errors.quantity" style="color: #ff4d4f; margin-left: 110px; margin-top: 5px; font-size: 12px;">
                    {{ errors.quantity }}
                </div>
            </div>

            <div class="form-item">
                <label class="form-label">单价</label>
                <input type="number" class="form-control input-number" v-model="form.price" min="0.01" step="0.01" @blur="validate('price')">
                <div v-if="errors.price" style="color: #ff4d4f; margin-left: 110px; margin-top: 5px; font-size: 12px;">
                    {{ errors.price }}
                </div>
            </div>

            <div class="form-item">
                <label class="form-label">备注</label>
                <textarea class="form-control" v-model="form.remark" rows="3" maxlength="500"></textarea>
            </div>
        </div>
        <div class="dialog-footer">
            <button class="btn btn-default" @click="dialogVisible = false">取消</button>
            <button class="btn btn-primary" @click="submitForm">确定</button>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            dialogVisible: false,
            dialogTitle: "添加入库记录",
            form: {
                supplier: '',
                productId: '',
                quantity: 1,
                price: 0.01,
                remark: ''
            },
            errors: {},
            selectedRows: [], // 存储选中的行数据
            products: [],
            supplierlist: [],
            searchForm: {
                productName: '',
                id: '',
                createTime: '' // 单个创建日期，格式YYYY-mm-dd
            },
            tableData: [],
            pageNum: 1,
            pageSize: 10,
            total: 0
        },
        computed: {
            totalPages() {
                // 计算总页数（至少1页）
                return Math.max(1, Math.ceil(this.total / this.pageSize));
            },
            pageNumbers() {
                // 生成显示的页码列表（最多显示5个页码，其余用...代替）
                const pages = [];
                const total = this.totalPages;
                const current = this.pageNum;

                // 总页数小于等于5时，显示所有页码
                if (total <= 5) {
                    for (let i = 1; i <= total; i++) {
                        pages.push(i);
                    }
                    return pages;
                }

                // 总页数大于5时，显示当前页附近的页码
                pages.push(1); // 显示第1页

                // 当前页在前面部分
                if (current <= 3) {
                    pages.push(2, 3, 4, '...', total);
                }
                // 当前页在中间部分
                else if (current >= total - 2) {
                    pages.push('...', total - 3, total - 2, total - 1, total);
                }
                // 当前页在中间位置
                else {
                    pages.push('...', current - 1, current, current + 1, '...', total);
                }

                return pages;
            }
        },
        created() {
            this.loadData();
            this.loadCategories();
            this.loadCatesupplier();
        },
        methods: {
            // 格式化价格
            formatPrice(value) {
                return value ? '¥' + parseFloat(value).toFixed(2) : '¥0.00';
            },

            // 获取状态文本
            getStatusText(status) {
                switch(status) {
                    case 1: return '未通过';
                    case 2: return '待审核';
                    case 0: return '入库通过';
                    default: return '未知状态';
                }
            },

            // 获取状态样式
            getStatusCode(status) {
                switch(status) {
                    case 1: return 'status-tag status-pending';
                    case 2: return 'status-tag status-review';
                    case 0: return 'status-tag status-passed';
                    default: return 'status-tag';
                }
            },

            // 全选/取消全选
            checkAll(event) {
                this.tableData.forEach(row => {
                    row.checked = event.target.checked;
                });
                this.updateSelectedRows();
            },

            // 单个勾选
            handleCheck(row) {
                this.updateSelectedRows();
            },

            // 更新选中的行
            updateSelectedRows() {
                this.selectedRows = this.tableData.filter(row => row.checked);
            },

            // 批量入库逻辑
            batchStockIn() {
                // 1. 检查是否有选中项
                if (this.selectedRows.length === 0) {
                    alert("请先勾选需要审核入库的记录");
                    return;
                }

                // 2. 筛选未入库的记录（status=1表示未通过）
                const unprocessed = this.selectedRows.filter(row => row.status === 1);
                if (unprocessed.length === 0) {
                    alert("选中的记录均已审核或无需审核");
                    return;
                }

                // 3. 提取未入库记录的inId列表
                const stockInDetails = unprocessed.map(row => ({inId: row.inId}));

                // 4. 批量提交审核
                axios.put("/stockIn/batch", stockInDetails)
                    .then(response => {
                        if (response.data.code === 200) {
                            alert("批量提交成功");
                            this.loadData(); // 刷新表格
                        } else {
                            alert("批量提交失败：" + (response.data.msg || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('提交失败:', error);
                        alert('系统错误');
                    });
            },

            // 显示添加对话框
            showAddDialog() {
                this.dialogTitle = "添加入库记录";
                this.dialogVisible = true;
                // 重置表单
                this.form = {
                    supplier: '',
                    productId: '',
                    quantity: 1,
                    price: 0.01,
                    remark: ''
                };
                this.errors = {};
            },

            // 表单验证
            validate(field) {
                this.errors[field] = '';
                switch(field) {
                    case 'supplier':
                        if (!this.form.supplier) {
                            this.errors[field] = '请选择供应商名称';
                        }
                        break;
                    case 'productId':
                        if (!this.form.productId) {
                            this.errors[field] = '请选择入库商品';
                        }
                        break;
                    case 'quantity':
                        if (!this.form.quantity || this.form.quantity < 1) {
                            this.errors[field] = '入库数量必须大于0';
                        }
                        break;
                    case 'price':
                        if (!this.form.price || this.form.price < 0.01) {
                            this.errors[field] = '单价必须大于0';
                        }
                        break;
                }
                return !this.errors[field];
            },

            // 全表单验证
            validateForm() {
                let isValid = true;
                ['supplier', 'productId', 'quantity', 'price'].forEach(field => {
                    if (!this.validate(field)) {
                        isValid = false;
                    }
                });
                return isValid;
            },

            // 提交表单
            submitForm() {
                if (!this.validateForm()) {
                    return;
                }

                axios.post('/stockIn/insertSatockIn', this.form)
                    .then(response => {
                        if (response.data.code === 200) {
                            alert('添加成功');
                            this.dialogVisible = false;
                            this.loadData();
                        } else {
                            alert(response.data.msg || '添加失败');
                        }
                    })
                    .catch(error => {
                        console.error('提交失败:', error);
                        alert('系统错误，添加失败');
                    });
            },

            // 加载数据（包含单个创建日期筛选）
            loadData() {
                const params = {
                    pageNo: this.pageNum,
                    pageSize: this.pageSize,
                    data: {
                        productName : this.searchForm.productName,
                        id : this.searchForm.id,
                        createTime: this.searchForm.createTime
                    }
                };

                axios.post('/stockIn/list', params)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.tableData = response.data.data.list || [];
                            this.total = response.data.data.total || 0;
                            // 初始化复选框状态
                            this.tableData.forEach(row => {
                                row.checked = false;
                            });
                            this.selectedRows = [];
                        } else {
                            alert(response.data.msg || '加载数据失败');
                        }
                    })
                    .catch(error => {
                        console.error('请求错误:', error);
                        alert('系统错误');
                    });
            },

            // 重置搜索条件
            resetSearch() {
                this.searchForm = {
                    productName: '',
                    id: '',
                    createTime: ''
                };
                this.pageNum = 1;
                this.loadData();
            },

            // 加载商品数据
            loadCategories() {
                axios.post('/product/list')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.products = response.data.data.list || [];
                        } else {
                            alert(response.data.msg || '加载商品数据失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('系统错误');
                    });
            },

            // 加载供应商数据
            loadCatesupplier() {
                axios.post('/supplier/listStatus')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.supplierlist = response.data.data || [];
                        } else {
                            alert(response.data.msg || '加载供应商数据失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('系统错误');
                    });
            },

            // 改变页码
            changePage(num) {
                // 验证页码有效性
                if (num < 1 || num > this.totalPages) return;
                this.pageNum = num;
                this.loadData();
            },

            // 处理每页条数变化
            handleSizeChange() {
                this.pageNum = 1; // 重置到第一页
                this.loadData();
            },

            // 处理编辑（提交审核）
            handleEdit(row) {
                if (confirm('确认将该商品提交审核吗？')) {
                    axios.put('/stockIn/update', row)
                        .then(response => {
                            if (response.data.code === 200) {
                                alert('已提交审核');
                                this.loadData();
                            } else {
                                alert(response.data.msg || '操作失败');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('系统错误');
                        });
                }
            },

            // 处理删除
            handleDelete(row) {
                if (confirm('确认删除该入库记录吗？')) {
                    axios.get('/stockIn/delete/' + row.inId)
                        .then(response => {
                            if (response.data.code === 200) {
                                alert('删除成功');
                                this.loadData();
                            } else {
                                alert(response.data.msg || '删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('系统错误');
                        });
                }
            }
        }
    });
</script>
</body>
</html>